﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace WpfPropertyEditorExtension
{
    public class XamlElementModel
    {
        // 用于回写时匹配：元素名 + 起始行（粗略匹配）
        [Browsable(false)]
        public string ElementName { get; set; } = "";

        [Browsable(false)]
        public int StartLine { get; set; }

        [Category("Layout")]
        public string Width { get; set; }

        [Category("Layout")]
        public string Height { get; set; }

        [Category("Common")]
        [DisplayName("x:Name")]
        public string Name { get; set; }

        [Category("Content")]
        public string Content { get; set; }

        public static XamlElementModel FromXElement(XElement el)
        {
            var model = new XamlElementModel
            {
                ElementName = el.Name.ToString(),
                StartLine = (el as IXmlLineInfo)?.LineNumber ?? 0,
                Width = (string)el.Attribute("Width"),
                Height = (string)el.Attribute("Height"),
                Name = (string)el.Attribute(XName.Get("Name"))
            };

            // 尝试读取简单内容
            if (!el.HasElements)
                model.Content = el.Value;

            return model;
        }

        public void ApplyTo(XElement el)
        {
            SetAttr(el, "Width", Width);
            SetAttr(el, "Height", Height);
            SetAttr(el, XName.Get("Name", "http://schemas.microsoft.com/winfx/2006/xaml"), Name);

            if (!el.HasElements)
            {
                el.Value = Content ?? string.Empty;
            }
        }

        private static void SetAttr(XElement el, XName name, string value)
        {
            if (value == null)
            {
                el.Attribute(name)?.Remove();
            }
            else
            {
                el.SetAttributeValue(name, value);
            }
        }

        private static void SetAttr(XElement el, string name, string value)
            => SetAttr(el, (XName)name, value);
    }
}
